package com.lishe.lishe.lishe.module.myorder.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.lishe.base.common.config.Constants;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.CommonUtils;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.myorder.adapter.OrderDetailAdapter;
import com.lishe.lishe.lishe.module.myorder.bean.OrderDetatilBean;
import com.lishe.lishe.lishe.module.myorder.presenter.OrderPresenter;
import com.lishe.lishe.lishe.module.myorder.view.RemindSendDialog;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.utils.DefaultCountDownTimer;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.FullyLinearLayoutManager;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.retrofit.BaseRequestBody;
import com.lishe.lishe.retrofit.DataResponseListener;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 订单详情
 * by bin
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private String mTid;
    private String mPaymentId;
    private TextView mTvOrderStatus;
    private TextView mTvOrderDesc;
    private TextView mTvPrice;
    private TextView mTvTotalPrice;
    private TextView mTvFeight;
    private TextView mTvCoupon;
    private TextView mTvOrderNum;
    private TextView mTvOrderTime;
    private TextView mTvName;
    private TextView mTvPhone;
    private TextView mTvAddress;
    private TextView mTvLogisticsInfo;
    private TextView mTvLogisticsTime;
    private OrderDetatilBean mOrderDetatilBean;
    private RecyclerView mRecyclerView;
    private TextView mPayButton;
    private TextView mCancleButton;
    private View mCouponLayout;
    private View mBottomLayout;
    private View mContentLayout;
    private DefaultCountDownTimer payTimer;
    private TextView mCouponText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        mTid = getIntent().getStringExtra(Constants.TID);
        mPaymentId = getIntent().getStringExtra(Constants.PAYMENTID);
        initView();
        getData();
    }

    private void initView() {
        TextView title = findViewById(R.id.title_text_title);
        title.setText("订单详情");
        findViewById(R.id.title_left_button).setOnClickListener(this);

        mBottomLayout = findViewById(R.id.bottom_layout);
        mContentLayout = findViewById(R.id.content_layout);

        mTvOrderStatus = findViewById(R.id.order_status);
        mTvOrderDesc = findViewById(R.id.order_desc);
        findViewById(R.id.logistics_layout).setOnClickListener(this);

        mTvLogisticsInfo = findViewById(R.id.logistics_info);
        mTvLogisticsTime = findViewById(R.id.logistics_time);

        mTvName = findViewById(R.id.receive_name);
        mTvPhone = findViewById(R.id.receive_phone);
        mTvAddress = findViewById(R.id.receive_address);

        mRecyclerView = findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setLayoutManager(new FullyLinearLayoutManager(this));

        mTvPrice = findViewById(R.id.price);
        mTvTotalPrice = findViewById(R.id.totalprice);
        mTvFeight = findViewById(R.id.freight);
        mTvCoupon = findViewById(R.id.coupon);
        mCouponText = findViewById(R.id.coupon_text);
        mCouponLayout = findViewById(R.id.coupon_layout);

        findViewById(R.id.qq_area).setOnClickListener(this);
        findViewById(R.id.phone_area).setOnClickListener(this);
        mTvOrderNum = findViewById(R.id.ordernum);
        mTvOrderTime = findViewById(R.id.ordertime);

        mPayButton = findViewById(R.id.pay_button);
        mCancleButton = findViewById(R.id.cancle_button);
        mPayButton.setOnClickListener(this);
        mCancleButton.setOnClickListener(this);
    }

    public void getData() {
        mContentLayout.setVisibility(View.GONE);
        mBottomLayout.setVisibility(View.GONE);
        LoadingUtils.createLoadingDialog(this, "加载中...", true);
        OrderPresenter.getInstance().getOrderDetail(mTid, mPaymentId, new DataResponseListener<OrderDetatilBean>() {
            @Override
            public void onSuccess(OrderDetatilBean bean) {
                mOrderDetatilBean = bean;
                initLogistics(bean.getData().getOrder_status());

                mTvName.setText("收货人：" + bean.getData().getAddr().getReceiver_name());
                mTvPhone.setText(bean.getData().getAddr().getReceiver_mobile());
                mTvAddress.setText("收货地址：" + bean.getData().getAddr().getReceiver_address());

                mRecyclerView.setAdapter(new OrderDetailAdapter(OrderDetailActivity.this, bean.getData().getTrade_paybillData()));

                mTvPrice.setText(FormatUtil.numFormat(Double.parseDouble(bean.getData().getMoney()) * 100) + "积分");
                mTvTotalPrice.setText("¥" + bean.getData().getProducts_price());
                mTvFeight.setText("¥" + bean.getData().getPost_fee());
                if ("0".equals(bean.getData().getPost_fee())) {
                    mTvFeight.setText("包邮");
                }
                mTvCoupon.setText("-¥" + bean.getData().getCoupon_relief());
                if ("0".equals(bean.getData().getCoupon_relief())) {
                    mCouponLayout.setVisibility(View.GONE);
                    mCouponText.setText("应付总额（积分） =（商品总价+运费）x100");
                } else {
                    mCouponLayout.setVisibility(View.VISIBLE);
                    mCouponText.setText("应付总额（积分） =（商品总价+运费-优惠券）x100");
                }
                if ("1".equals(bean.getData().getOrder_status()) || "2".equals(bean.getData().getOrder_status())
                        || "3".equals(bean.getData().getOrder_status()) || "4".equals(bean.getData().getOrder_status())) {
                    mTvOrderNum.setText("订单编号：" + bean.getData().getPayment_id());
                } else {
                    mTvOrderNum.setText("订单编号：" + bean.getData().getTrade_paybillData().get(0).getTid());
                }
                SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                Date date = new Date(Long.parseLong(bean.getData().getCreated_time()) * 1000);
                mTvOrderTime.setText("下单时间：" + format.format(date));

                mContentLayout.setVisibility(View.VISIBLE);
                mBottomLayout.setVisibility(View.VISIBLE);
                initOrderStatus(bean.getData().getOrder_status());
                LoadingUtils.closeDialog();
            }

            @Override
            public void onFail(String failMessage) {
                LoadingUtils.closeDialog();
                ToastUtil.showToast(OrderDetailActivity.this, failMessage);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                LoadingUtils.closeDialog();
                ToastUtil.showToast(OrderDetailActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    // 初始化物流信息
    private void initLogistics(String order_status) {
        switch (order_status) {
            case "6"://待收货
            case "7"://待评论
            case "8"://已完成
                if (mOrderDetatilBean.getData().getExpress() == null || mOrderDetatilBean.getData().getExpress().getSteps().size() == 0) {
                    mTvLogisticsInfo.setText("暂无最新物流信息");
                    mTvLogisticsTime.setVisibility(View.GONE);
                } else {
                    mTvLogisticsInfo.setText(mOrderDetatilBean.getData().getExpress().getSteps().get(0).getNote());
                    mTvLogisticsTime.setText(mOrderDetatilBean.getData().getExpress().getSteps().get(0).getTime());
                }
                findViewById(R.id.logistics_layout).setVisibility(View.VISIBLE);
                break;
            case "1"://超时失效
            case "2"://用户手动取消
            case "3"://被客服取消
            case "4"://待付款
            case "5"://待发货
            case "9"://退货
            default: //未知状态
                findViewById(R.id.logistics_layout).setVisibility(View.GONE);
                break;
        }
    }

    private void initOrderStatus(String order_status) {
        mCancleButton.setEnabled(true);
        mCancleButton.setTextColor(context.getResources().getColor(R.color.gray_3));
        switch (order_status) {
            case "1"://超时失效
                mTvOrderStatus.setText("已取消");
                mTvOrderDesc.setText("支付超时，订单自动失效");

               /* mPayButton.setVisibility(View.GONE);
                mCancleButton.setText("删除订单");*/
                mBottomLayout.setVisibility(View.GONE);
                break;
            case "2"://用户手动取消
                mTvOrderStatus.setText("已取消");
                mTvOrderDesc.setText("用户主动取消订单");

                mBottomLayout.setVisibility(View.GONE);
                break;
            case "3"://被客服取消
                mTvOrderStatus.setText("已取消");
                mTvOrderDesc.setText("客服取消订单");

                mBottomLayout.setVisibility(View.GONE);
                break;
            case "4"://待付款
                mTvOrderStatus.setText("待付款");
                long _30min = 60 * 30 * 1000;
                long d1 = Long.parseLong(mOrderDetatilBean.getData().getSys_time()) * 1000;
                long d2 = Long.parseLong(mOrderDetatilBean.getData().getCreated_time()) * 1000;
                long diff = _30min - (d1 - d2);
                DefaultCountDownTimer timer = new DefaultCountDownTimer(mTvOrderDesc, "您的订单已提交，请在",
                        "内完成支付，超时订单将自动取消", diff, 1000, new DefaultCountDownTimer.Finish() {
                    @Override
                    public void onFinish() {}
                });
                timer.setForOrderDetail(true);
                timer.start();

                payTimer = new DefaultCountDownTimer(mPayButton, "付款 ",
                        "", diff, 1000, new DefaultCountDownTimer.Finish() {
                    @Override
                    public void onFinish() {
                        finish();
                    }
                });
                payTimer.start();
                break;
            case "5"://待发货
                mTvOrderStatus.setText("待发货");
                mTvOrderDesc.setText("您的订单支付成功，等待商家发货");

                mPayButton.setVisibility(View.GONE);
                mCancleButton.setText("催发货");

                if (getIntent().getBooleanExtra(Constants.ISREMINDSEND, false)) {
                    mCancleButton.setEnabled(false);
                    mCancleButton.setTextColor(context.getResources().getColor(R.color.gray_9));
                }
                break;
            case "6"://待收货
                mTvOrderStatus.setText("已发货");
                mTvOrderDesc.setText("待确认收货");

                mPayButton.setText("确认收货");
                mCancleButton.setText("查看物流");
                break;
            case "7"://待评论
            case "8"://已完成
                mTvOrderStatus.setText("交易成功");
                mTvOrderDesc.setText("宝贝已送达，感谢光临~");

                mPayButton.setVisibility(View.GONE);
                mCancleButton.setText("删除订单");
                mBottomLayout.setVisibility(View.GONE);
                break;
            case "9"://退货
                mTvOrderStatus.setText("退货");
                mTvOrderDesc.setText("有问题可以联系客服哟~~");

                mPayButton.setVisibility(View.GONE);
                mCancleButton.setText("删除订单");
                mBottomLayout.setVisibility(View.GONE);
                break;
            default:
                mTvOrderStatus.setText("未知状态");
                mTvOrderDesc.setText("未知状态");

                mPayButton.setVisibility(View.GONE);
                mCancleButton.setText("删除订单");
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.logistics_layout:
                LogisticsActivity.jump(this, mOrderDetatilBean.getData().getTrade_paybillData().get(0).getTid());
                break;
            case R.id.qq_area:
                CommonUtils.gotoQQ(this, mOrderDetatilBean.getData().getCustomer().getQq());
                break;
            case R.id.phone_area:
                ConfirmDialog.Builder callPhoneDialog = new ConfirmDialog.Builder(context);
                callPhoneDialog.setContent(mOrderDetatilBean.getData().getCustomer().getPhoneNumber());
                callPhoneDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
                callPhoneDialog.setPositiveButton("确定", new ConfirmDialog.Builder.OnPositiveListener() {
                    @Override
                    public void onPositive(ConfirmDialog dialog) {
                        dialog.dismiss();
                        CommonUtils.callPhone((Activity) context, mOrderDetatilBean.getData().getCustomer().getPhoneNumber());
                    }
                });
                callPhoneDialog.show();
                break;
            case R.id.pay_button:
                switch (mOrderDetatilBean.getData().getOrder_status()) {
                    case "4"://待付款---立即付款
                        PayActivity.jump(this, mOrderDetatilBean.getData().getPayment_id(),
                                mOrderDetatilBean.getData().getCreated_time(), mOrderDetatilBean.getData().getMoney());
                        break;
                    case "6"://待收货---确认收货
                        showSureConfirmDialog(mOrderDetatilBean.getData().getPayment_id());
                        break;
                }
                break;
            case R.id.cancle_button://催发货, 取消订单
                switch (mOrderDetatilBean.getData().getOrder_status()) {
                    case "5"://待发货---催发货
                        new RemindSendDialog(this).show();
                        mCancleButton.setEnabled(false);
                        mCancleButton.setTextColor(getResources().getColor(R.color.gray_9));
                        break;
                    case "6"://待收货---查看物流
                        LogisticsActivity.jump(this, mOrderDetatilBean.getData().getTrade_paybillData().get(0).getTid());
                        break;
                    case "1"://超时失效
                    case "2"://用户手动取消
                    case "3"://被客服取消
                    case "7"://待评论
                    case "8"://已完成
                    case "9"://退货---删除订单
                    default:
                        showCancelOrderDialog(mOrderDetatilBean.getData().getPayment_id());
                        break;
                }
                break;
        }
    }

    /**
     * 确认收货
     */
    private void confirmOrder(String paymentId) {
        LoadingUtils.createLoadingDialog(this, "加载中...", false);
        OrderPresenter.getInstance().confirmOrder(Globals.getToken(), paymentId, new DataResponseListener<BaseRequestBody>() {
            @Override
            public void onSuccess(BaseRequestBody dataResponse) {
                ToastUtil.showToast(OrderDetailActivity.this, dataResponse.getMsg());
                LoadingUtils.closeDialog();
                getData();
            }

            @Override
            public void onFail(String failMessage) {
                ToastUtil.showToast(OrderDetailActivity.this, failMessage);
                LoadingUtils.closeDialog();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(OrderDetailActivity.this, "取消失败，服务器或网络异常！");
                LoadingUtils.closeDialog();
            }
        });
    }

    /**
     * 确认收货dialog
     */
    private void showSureConfirmDialog(final String payment_id) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("订单确认收货")
                .setMessage("确认收到货物了再点哦~")
                .setPositiveButton("确认收货", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        confirmOrder(payment_id);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(context.getResources().getColor(R.color.color_ff4138));
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.gray_6));
    }

    /**
     * 取消订单dialog
     */
    private void showCancelOrderDialog(final String payment_id) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("订单取消确认")
                .setMessage("取消了可能会被抢光哟~")
                .setPositiveButton("仍然取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        cancleOrder(payment_id);
                    }
                })
                .setNegativeButton("我再想想", null)
                .show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(context.getResources().getColor(R.color.color_ff4138));
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.gray_6));
    }

    /**
     * 取消订单
     */
    private void cancleOrder(String paymentId) {
        OrderPresenter.getInstance().cancelOrder(Globals.getToken(), paymentId, new DataResponseListener<BaseRequestBody>() {
            @Override
            public void onSuccess(BaseRequestBody dataResponse) {
                ToastUtil.showToast(OrderDetailActivity.this, dataResponse.getMsg());
                finish();
            }

            @Override
            public void onFail(String failMessage) {
                ToastUtil.showToast(OrderDetailActivity.this, failMessage);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(OrderDetailActivity.this, "取消失败，服务器或网络异常！");
            }
        });
    }

}
